


<template>
  <div class="app">
    <div class="content">
      <el-form
        :label-position="labelPosition"
        label-width="80px"
        :model="fatherObj"
      >
        <div class="title">基础信息</div>
        <el-form-item label="商品名称">
          <el-input v-model="fatherObj.name" class="input"></el-input>
        </el-form-item>
        <el-form-item label="商品编号">
          <el-input v-model="fatherObj.bn" class="input"></el-input>
        </el-form-item>
        <el-form-item label="商品单位">
          <el-input v-model="fatherObj.unit" class="input"></el-input>
        </el-form-item>

        <el-form-item label="商品品牌">
          <el-select
            v-model="fatherObj.brand_id"
            placeholder="品牌"
            class="input"
            @change="selectChange"
          >
            <el-option
              v-for="(item, index) in pinpaiList"
              :key="index"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="商品分类">
          <!--            <el-select v-model="fatherObj.goods_cat_id" placeholder="分类" class="input">-->
          <!--              <el-option  v-for="(item,index) in fenleiList" :key="index" :label="item.name" :value="item.id"></el-option>-->
          <!--            </el-select>-->
          <el-cascader
            class="input"
            v-model="selectfenleiList"
            :props="fenleiListProps"
            :options="fenleiList"
            :show-all-levels="false"
            @change="handleChange"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="商品照片" prop="images">
          <el-form-item label="">
            <div class="unlodBox">
              <el-upload
                class="upload-demo"
                action
                :multiple="true"
                :http-request="uploadFile"
                ref="upload"
                :limit="fileLimit"
                :on-remove="handleRemove"
                :file-list="fileList"
                :on-exceed="handleExceed"
                :before-upload="beforeUpload"
                :show-file-list="false"
                :headers="headers"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">
                  预览图：[第一张图片为默认图，可拖动图片进行排序]
                </div>
              </el-upload>

              <ul class="list">
                <transition-group name="drag" class="list" tag="ul">
                  <li
                    @dragenter="dragenter($event, index)"
                    @dragover="dragover($event, index)"
                    @dragstart="dragstart(index)"
                    draggable
                    v-for="(item, index) in fatherObj.imagesquan"
                    :key="index + 1"
                    class="list-item"
                  >
                    <el-image
                      draggable="true"
                      v-if="fatherObj.imagesquan.length > 0"
                      style="
                        width: 100px;
                        height: 100px;
                        margin: 0 10px;
                        border: 1px solid #ccc;
                        padding: 10px;
                      "
                      :key="index"
                      :src="item"
                      fit="cover"
                    ></el-image>
                    <div @click="deleteImg(index)" class="deleteImg">删除</div>
                  </li>
                </transition-group>
              </ul>
            </div>
          </el-form-item>
        </el-form-item>
        <!--          <el-form-item label="">-->
        <!--            <el-image-->
        <!--              style="width: 100px; height: 100px"-->
        <!--              :src="image"-->
        <!--              fit="cover"-->
        <!--            ></el-image>-->
        <!--          </el-form-item>-->
        <div class="title">销售信息</div>
        <el-form-item label="销售价">
          <el-input v-model="fatherObj.price" class="input"></el-input>
        </el-form-item>
        <el-form-item label="成本价">
          <el-input v-model="fatherObj.costprice" class="input"></el-input>
        </el-form-item>
        <el-form-item label="市场价">
          <el-input v-model="fatherObj.mktprice" class="input"></el-input>
        </el-form-item>
        <el-form-item label="重量">
          <el-input
            v-model="fatherObj.weight"
            class="input"
            placeholder="请输入重量;单位/千克"
          ></el-input>
          &nbsp;/千克
        </el-form-item>
        <el-form-item label="库存">
          <el-input v-model="fatherObj.stock" class="input"></el-input>
        </el-form-item>

        <el-form-item label="长度" prop="lengthc">
          <el-input
            type="number"
            v-model="fatherObj.lengthc"
            class="input"
            @input="lenthc"
          ></el-input>
          /cm
        </el-form-item>
        <el-form-item label="宽度" prop="width">
          <el-input
            type="number"
            v-model="fatherObj.width"
            class="input"
          ></el-input>
          /cm
        </el-form-item>
        <el-form-item type="number" label="高度" prop="height">
          <el-input v-model="fatherObj.height" class="input"></el-input> /cm
        </el-form-item>
        <el-form-item label="颜色" prop="colour">
          <el-input v-model="fatherObj.colour" class="input"></el-input>
        </el-form-item>
        <el-form-item type="number" label="体积" prop="volume">
          <el-input v-model="fatherObj.volume" class="input"></el-input> /cm
        </el-form-item>
        <el-form-item type="number" label="型号" prop="model">
          <el-input v-model="fatherObj.model" class="input"></el-input> /cm
        </el-form-item>
        <el-form-item label="上下架">
          <el-switch
            v-model="fatherObj.marketable"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :active-value="1"
            :inactive-value="2"
            @change="switchChange(fatherObj.marketable)"
          >
          </el-switch>
        </el-form-item>
        <el-form-item label="热门">
          <el-switch
            v-model="fatherObj.is_hot"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :active-value="1"
            :inactive-value="2"
            @change="switchChange2(fatherObj.is_hot)"
          >
          </el-switch>
        </el-form-item>
        <el-form-item type="number" label="详细介绍" prop="intro">
          <el-upload
            class="upload-demo editorUpload"
            action
            :http-request="uploadFile3"
            ref="editorUpload"
            :limit="fileLimit3"
            :on-remove="handleRemove3"
            :file-list="fileList3"
            :on-exceed="handleExceed"
            :before-upload="beforeUpload2"
            :show-file-list="false"
            :headers="headers"
          >
          </el-upload>
          <quill-editor
            v-model="content"
            ref="myQuillEditor"
            :height="200"
            :options="editorOption"
            @blur="onEditorBlur($event)"
            @focus="onEditorFocus($event)"
            @change="onEditorChange($event)"
            @ready="onEditorReady($event)"
          >
          </quill-editor>
        </el-form-item>
      </el-form>
    </div>
    <div class="footer">
      <el-button @click="save">保存</el-button>
      <el-button @click="back">返回</el-button>
    </div>
  </div>
</template>

<script>
import {
  allBrand,
  goodSort,
  uploadFilec,
  saveGoodSetmo,
} from "../../utils/api";
import { quillEditor } from "vue-quill-editor";

import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
var _EditorOption_ = {
  modules: {
    toolbar: {
      container: [
        ["bold", "italic", "underline", "strike"], // 加粗 斜体 下划线 删除线
        ["blockquote", "code-block"],
        [{ header: 1 }, { header: 2 }], //// 1、2 级标题-----[{ header: 1 }, { header: 2 }]
        // [{ size: ['small', false, 'large', 'huge'] }],// 字体大小
        [
          {
            size: ["12", "14", "16", "18", "20", "22", "24", "28", "32", "36"],
          },
        ], // 字体大小
        [{ color: [] }, { background: [] }], // 字体颜色、字体背景颜色
        [{ align: [] }], // 对齐方式
        ["clean"], // 清除文本格式
        // ['link','image'] // 链接、图片、视频

        [{ header: [1, 2, 3, 4, 5, 6, false] }], //// 标题-----[{ header: [1, 2, 3, 4, 5, 6, false] }]
        // 缩进-----[{ indent: '-1' }, { indent: '+1' }]
        [{ indent: "-1" }, { indent: "+1" }],
        // 有序、无序列表-----[{ list: 'ordered' }, { list: 'bullet' }]
        [{ list: "ordered" }, { list: "bullet" }],
        // 上标/下标-----[{ script: 'sub' }, { script: 'super' }]
        [{ script: "sub" }, { script: "super" }],
        // 文本方向-----[{'direction': 'rtl'}]
        [{ direction: "rtl" }],
        // 字体大小-----[{ size: ['small', false, 'large', 'huge'] }]
        // [{ size: ['small', false, 'large', 'huge'] }],
        // ['link', 'image'],  // 上传图片、上传视频
        ["image"], // 上传图片、上传视频
      ],
      handlers: {
        image: (value) => {
          if (value) {
            document.querySelector(".editorUpload input").click();
          } else {
            this.quill.format("image", false);
          }
        },
        link: function (value) {
          if (value) {
            // console.log(this.quill)
          } else {
            this.quill.format("link", false);
          }
        },
      },
    },
    history: {
      delay: 1000,
      maxStack: 50,
      userOnly: false,
    },
  },
  placeholder: "请输入正文",
  readyOnly: false, //是否只读
  theme: "snow", //主题 snow/bubble
  syntax: true, //语法检测
};
// toolbar标题
const titleConfig = [
  { Choice: ".ql-insertMetric", title: "跳转配置" },
  { Choice: ".ql-bold", title: "加粗" },
  { Choice: ".ql-italic", title: "斜体" },
  { Choice: ".ql-underline", title: "下划线" },
  { Choice: ".ql-header", title: "段落格式" },
  { Choice: ".ql-strike", title: "删除线" },
  { Choice: ".ql-blockquote", title: "块引用" },
  { Choice: ".ql-code", title: "插入代码" },
  { Choice: ".ql-code-block", title: "插入代码段" },
  { Choice: ".ql-font", title: "字体" },
  { Choice: ".ql-size", title: "字体大小" },
  { Choice: '.ql-list[value="ordered"]', title: "编号列表" },
  { Choice: '.ql-list[value="bullet"]', title: "项目列表" },
  { Choice: ".ql-direction", title: "文本方向" },
  { Choice: '.ql-header[value="1"]', title: "h1" },
  { Choice: '.ql-header[value="2"]', title: "h2" },
  { Choice: ".ql-align", title: "对齐方式" },
  { Choice: ".ql-color", title: "字体颜色" },
  { Choice: ".ql-background", title: "背景颜色" },
  { Choice: ".ql-image", title: "图像" },
  { Choice: ".ql-video", title: "视频" },
  { Choice: ".ql-link", title: "添加链接" },
  { Choice: ".ql-formula", title: "插入公式" },
  { Choice: ".ql-clean", title: "清除字体格式" },
  { Choice: '.ql-script[value="sub"]', title: "下标" },
  { Choice: '.ql-script[value="super"]', title: "上标" },
  { Choice: '.ql-indent[value="-1"]', title: "向左缩进" },
  { Choice: '.ql-indent[value="+1"]', title: "向右缩进" },
  { Choice: ".ql-header .ql-picker-label", title: "标题大小" },
  { Choice: '.ql-header .ql-picker-item[data-value="1"]', title: "标题一" },
  { Choice: '.ql-header .ql-picker-item[data-value="2"]', title: "标题二" },
  { Choice: '.ql-header .ql-picker-item[data-value="3"]', title: "标题三" },
  { Choice: '.ql-header .ql-picker-item[data-value="4"]', title: "标题四" },
  { Choice: '.ql-header .ql-picker-item[data-value="5"]', title: "标题五" },
  { Choice: '.ql-header .ql-picker-item[data-value="6"]', title: "标题六" },
  { Choice: ".ql-header .ql-picker-item:last-child", title: "标准" },
  { Choice: '.ql-size .ql-picker-item[data-value="small"]', title: "小号" },
  { Choice: '.ql-size .ql-picker-item[data-value="large"]', title: "大号" },
  { Choice: '.ql-size .ql-picker-item[data-value="huge"]', title: "超大号" },
  { Choice: ".ql-size .ql-picker-item:nth-child(2)", title: "标准" },
  { Choice: ".ql-align .ql-picker-item:first-child", title: "居左对齐" },
  {
    Choice: '.ql-align .ql-picker-item[data-value="center"]',
    title: "居中对齐",
  },
  {
    Choice: '.ql-align .ql-picker-item[data-value="right"]',
    title: "居右对齐",
  },
  {
    Choice: '.ql-align .ql-picker-item[data-value="justify"]',
    title: "两端对齐",
  },
];
export default {
  name: "bianjiMaterials",
  props: {
    sonObj: {
      type: [Object, String, Number],
    },
  },
  components: {
    quillEditor,
  },
  data() {
    return {
      imgHeader: this.Global.imgHeader,

      editorOption: _EditorOption_,
      content: "",
      dragIndex: "",
      enterIndex: "",
      token: sessionStorage.getItem("token"),
      labelPosition: "right",
      pinpaiList: [],
      fenleiList: [],
      image: "",
      fatherObj: {
        imagesquan: [],
      },
      fenleiListProps: {
        label: "name",
        value: "id",
        children: "child",
      },
      selectfenleiList: [],
      fileLimit: 5,
      fileLimit3: 20,
      fileType: ["png", "jpg", "jpeg"],
      fileList: [],
      fileList3: [],
      headers: { "Content-Type": "multipart/form-data" },
      saveFlag: true,
    };
  },
  methods: {
    onEditorFocus(e) {},
    onEditorChange(e) {
      console.log(e);
      // if(e.html==this.form.yonghu.value){
      //   this.saveFlag = false
      // }else{
      //   this.saveFlag = true
      // }
      // if(e.html==this.form.yinsi.value){
      //   this.saveFlag = false
      // }else{
      //   this.saveFlag = true
      // }
    },
    onEditorReady(e) {},
    onEditorBlur(e) {},
    uploadFile3(item) {
      this.$message("文件上传中........");
      //上传文件的需要formdata类型;所以要转
      uploadFilec(item.file).then((res) => {
        if (res.data.status != false || res.data.id != null) {
          res.data.data.saveurl; //半截
          res.data.data.weburl; //全拼
          let quill = this.$refs.myQuillEditor.quill;
          let length = quill.getSelection().index;
          quill.insertEmbed(length, "image", res.data.data.weburl);
          quill.setSelection(length + 1);
          this.fileList3.push(item.file); //成功过后手动将文件添加到展示列表里
          let i = this.fileList3.indexOf(item.file);
          this.handleSuccess();
        }
      });
    },
    selectChange(e) {
      this.fatherObj.brand = this.pinpaiList.find((item) => {
        return item.id == e;
      }).name;
    },
    deleteImg(e) {
      this.fileList.splice(e, 1); //删除上传的文件
      this.fatherObj.imagesquan.splice(e, 1); //删除上传的文件
      this.fatherObj.images.splice(e, 1); //删除上传的文件
    },
    dragstart(index) {
      this.dragIndex = index;
    },
    dragenter(e, index) {
      e.preventDefault();
      // 避免源对象触发自身的dragenter事件
      if (this.dragIndex !== index) {
        const source = this.fatherObj.imagesquan[this.dragIndex];
        const source1 = this.fatherObj.images[this.dragIndex];
        this.fatherObj.imagesquan.splice(this.dragIndex, 1);
        this.fatherObj.images.splice(this.dragIndex, 1);
        this.fatherObj.imagesquan.splice(index, 0, source);
        this.fatherObj.images.splice(index, 0, source1);
        console.log(this.fatherObj);
        // 排序变化后目标对象的索引变成源对象的索引
        this.dragIndex = index;
      }
    },
    dragover(e, index) {
      e.preventDefault();
    },
    uploadFile(item) {
      this.$message("文件上传中........");
      //上传文件的需要formdata类型;所以要转
      uploadFilec(item.file).then((res) => {
        if (res.data.status != false || res.data.id != null) {
          res.data.data.saveurl; //半截
          res.data.data.weburl; //全拼
          this.fatherObj.imagesquan.push(res.data.data.weburl);
          this.fatherObj.images.push(res.data.data.saveurl);
          this.fileList.push(item.file); //成功过后手动将文件添加到展示列表里
          console.log(item.file);
          console.log(this.fileList);
          let i = this.fileList.indexOf(item.file);
          this.handleSuccess();
        }
      });
    },
    //上传成功后的回调
    handleSuccess() {
      this.$message({
        message: "上传成功",
        type: "success",
      });
      // this.handleClose()
    },
    handleRemove() {},
    handleRemove3() {},
    beforeUpload(file) {
      if (file.type != "" || file.type != null || file.type != undefined) {
        //截取文件的后缀，判断文件类型
        const FileExt = file.name.replace(/.+\./, "").toLowerCase();
        //计算文件的大小
        const isLt5M = file.size / 1024 / 1024 < 1; //这里做文件大小限制
        //如果大于50M
        if (!isLt5M) {
          this.$message.error("上传文件大小不能超过 1MB!");
          return false;
        }
        //如果文件类型不在允许上传的范围内
        if (this.fileType.includes(FileExt)) {
          return true;
        } else {
          this.$message.error("上传文件格式不正确!");
          return false;
        }
      }
    },
    beforeUpload2(file) {
      if (file.type != "" || file.type != null || file.type != undefined) {
        //截取文件的后缀，判断文件类型
        const FileExt = file.name.replace(/.+\./, "").toLowerCase();
        //计算文件的大小
        const isLt5M = file.size / 1024 / 1024 < 1; //这里做文件大小限制
        //如果大于50M
        if (!isLt5M) {
          this.$message.error("上传文件大小不能超过 1MB!");
          return false;
        }
        //如果文件类型不在允许上传的范围内
        if (this.fileType.includes(FileExt)) {
          return true;
        } else {
          this.$message.error("上传文件格式不正确!");
          return false;
        }
      }
    },
    handleClose3(i) {
      this.fileList.splice(i, 1); //删除上传的文件
    },
    handleClose(i) {
      this.fileList.splice(i, 1); //删除上传的文件
    },
    //超出文件个数的回调
    handleExceed() {
      this.$message({
        type: "warning",
        message: "超出最大上传文件数量的限制！",
      });
      return;
    },

    handleChange(e) {
      this.fatherObj.goods_cat_id = this.selectfenleiList[1];
      // console.log(e,)
    },
    unloadImg() {},
    goodsType(e) {},
    switchChange(e) {
      this.fatherObj.marketable = e;
    },
    switchChange2(e) {
      this.fatherObj.is_hot = e;
    },
    back() {
      this.$emit("back");
    },
    save() {
      if (!this.saveFlag) {
        return;
      }
      saveGoodSetmo(
        this.token,
        this.fatherObj.name,
        this.fatherObj.goods_cat_id,
        this.fatherObj.brand_id,
        this.fatherObj.brand,
        4,
        this.fatherObj.price,
        this.fatherObj.costprice,
        this.fatherObj.mktprice,
        this.fatherObj.weight,
        this.fatherObj.stock,
        this.fatherObj.unit,
        JSON.stringify(this.fatherObj.images),
        this.fatherObj.marketable,
        this.fatherObj.is_hot,
        this.fatherObj.id,
        this.fatherObj.bn,
        this.fatherObj.specifications,
        this.fatherObj.lengthc,
        this.fatherObj.width,
        this.fatherObj.height,
        this.fatherObj.colour,
        this.fatherObj.volume,
        this.fatherObj.model,
        JSON.stringify(this.fatherObj.intro)
      ).then((res) => {
        // console.log(res)
        this.saveFlag = false;
        if (res.data.status) {
          this.$message({
            message: "操作成功",
            type: "success",
          });
          this.$emit("back");
        } else {
          this.$message({
            message: res.data.msg,
            type: "error",
            onClose: (res) => {
              this.saveFlag = true;
            },
          });
          if (res.data.msg == "token失效,请重新进行登录") {
            this.$router.push("/login");
          }
        }
      });
    },
    lenthc(e) {},
    initialize() {
      let obj = JSON.parse(JSON.stringify(this.sonObj));
      obj.imagesquan = [];
      obj.lengthc = "";
      this.fatherObj = obj;
      console.log(this.fatherObj.intro);
      if (this.fatherObj.intro) {
        this.content = JSON.parse(this.fatherObj.intro);
      } else {
        this.content = "";
      }
      JSON.parse(this.fatherObj.images).forEach((item) => {
        this.fatherObj.imagesquan.push(this.imgHeader + item);
      });
      this.fatherObj.lengthc = obj.Length;
      console.log((this.fatherObj.images = JSON.parse(this.fatherObj.images)));
      allBrand(sessionStorage.getItem("token"), 2).then((res) => {
        if (res.data.status) {
          this.pinpaiList = res.data.data;
        } else {
          this.$message.error(res.data.msg);
        }
      });
      goodSort(sessionStorage.getItem("token"), 3, "").then((res) => {
        if (res.data.status) {
          this.fenleiList = res.data.data;
          this.fenleiList.forEach((item, index) => {
            item.child.forEach((item2, index2) => {
              if (item2.id == this.fatherObj.goods_cat_id) {
                this.selectfenleiList[0] = item.id;
                this.selectfenleiList[1] = item2.id;
              }
            });
          });
        } else {
          this.$message.error(res.data.msg);
        }
      });
      // this.fatherObj.imagesquan = 'https://bjsf.bjsky.top'+this.fatherObj.images
      // console.log(this.fatherObj)
      for (let key in this.fatherObj) {
        // if(key=='goods_type_id'){
        //   if(this.fatherObj[key]==1){
        //     this.fatherObj.goods_type_name = '桶装水'
        //   }
        //   if(this.fatherObj[key]==2){
        //     this.fatherObj.goods_type_name = '通用'
        //   }
        // }
      }
      // this.fatherObj.forEach((item,index)=>[
      //   console.log(item.goods_type_id==1)
      // ])
    },
  },
  created() {
    this.initialize();
  },

  watch: {
    content(n, o) {
      this.fatherObj.intro = n;
    },
  },
};
</script>

<style scoped>
.app {
  padding: 10px;
}
.content {
  box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.12), 0 0 6px 0 rgba(0, 0, 0, 0.04);

  max-height: 80vh;
  overflow: auto;
}

.footer {
  margin: 10px auto;
  width: 50%;
  display: flex;
  justify-content: center;
}
.el-form-item .input {
  width: 200px;
}
.title {
  display: block;
  margin-bottom: 20px;
  text-indent: 1em;
}
/deep/.upload-demo .el-upload--text {
  border: none;
  width: auto;
  height: auto;
}
.upload-demo {
  line-height: normal;
  margin-bottom: 20px;
}
ul,
li {
  list-style: none;
}
.list {
  display: flex;
}
.deleteImg {
  cursor: pointer;
  text-align: center;
}
</style>

